<?php

namespace App\V3\V3_1\Services;

use App\V3\V3_1\Models\StorageManageModel;
use App\V3\V3_1\Models\StorageModel;
use App\V3\V3_1\Models\StorageShelfLocationModel;
use App\V3\V3_1\Models\StorageShelfModel;

class StorageService
{
    //获取仓库列表
    static public function storageList($userId, $data)
    {
        return StorageModel::getStorageList($userId, $data);
    }

    //下拉列表
    static public function storageSelect($userId)
    {
        return StorageModel::getStorageSelect($userId);
    }

    //删除指定仓库
    static public function delete($data)
    {
        $storageInfo = StorageModel::where($data)->first();
        if(empty($storageInfo)) {
            return ['code' => 1, 'msg' => '目标仓库不存在，无法完成删除'];
        }

        $info = StorageManageModel::getStorageManagerInfoByStorageId($data['id']);

        if($info['is_product_storage']) {
            return ['code' => 1, 'msg' => '默认产品库，无法删除'];
        }

        //当前仓库中是否仍存在物料
        if($info['in_storage_num'] > 0) {
            return ['code' => 1, 'msg' => '当前仓库存在商品，请清空仓库后删除'];
        }
        else {
            StorageModel::where('id', $data['id'])->update(['delete_flag' => 1]);
            StorageManageModel::where('storage_id', $data['id'])->update(['delete_flag' => 1]);
            return ['code' => 0];
        }
    }

    static public function storageShelfLocation($data)
    {
        return StorageModel::select(
            'id',
            'id as storage_id',
            'storage_name',
            'storage_address'
        )
            ->with(['shelfList' => function($query) {
                $query->select(
                    'id',
                    'id as shelf_id',
                    'shelf_name',
                    'storage_id'
                )->with('locationList',function($query) {
                    $query->select(
                        'id as location_id',
                        'shelf_id',
                        'location_name'
                    );
                });
            }])
            ->where($data)->where('delete_flag', 0)->get();
    }

    public static function createDefaultProductStorage($mainUserId)
    {
        $productStorageInfo = StorageModel::where([
            'main_id' => $mainUserId,
            'is_product_storage' => 1,
        ])
            ->first();
        if(empty($productStorageInfo)) {
            $storageId = StorageModel::createDefaultProductStorage($mainUserId);
            $shelfId = StorageShelfModel::createDefaultProductShelf($mainUserId, $storageId);
            StorageShelfLocationModel::insert([
                'location_name' => '默认产品库库位',
                'is_product_shelf_location' => 1,
                'main_id' => $mainUserId,
                'storage_id' => $storageId,
                'shelf_id' => $shelfId,
                'created_at' => time(),
                'location_type' => 1
            ]);
        }
        return true;
    }
}
